#!/bin/sh
set -eu

ROOT="/usr/share/nginx/html"

# (A) Generate /runtime-config.js from container env (for future use / parity)
cat >"$ROOT/runtime-config.js.tmpl" <<'EOF'
window.runtimeConfig = {
  VITE_WEB_API_URL: "${VITE_WEB_API_URL}",
  VITE_WEB_SPARROW_SUPPORT_EMAIL: "${VITE_WEB_SPARROW_SUPPORT_EMAIL}",
  VITE_WEB_SPARROW_OAUTH: "${VITE_WEB_SPARROW_OAUTH}",
  VITE_WEB_ENABLE_MIX_PANEL: "${VITE_WEB_ENABLE_MIX_PANEL}",
  VITE_WEB_MIX_PANEL_TOKEN: "${VITE_WEB_MIX_PANEL_TOKEN}",
  VITE_WEB_TERMS_OF_SERVICE: "${VITE_WEB_TERMS_OF_SERVICE}",
  VITE_WEB_SPARROW_WEB_URL: "${VITE_WEB_SPARROW_WEB_URL}",
  VITE_WEB_SPARROW_ADMIN_URL: "${VITE_WEB_SPARROW_ADMIN_URL}",
  VITE_WEB_SPARROW_PRIVACY_POLICY: "${VITE_WEB_SPARROW_PRIVACY_POLICY}",
  VITE_WEB_CANNY_URL: "${VITE_WEB_CANNY_URL}",
  VITE_WEB_APP_EDITION: "${VITE_WEB_APP_EDITION}",
  VITE_WEB_SPARROW_CONTACT_SALES_URL: "${VITE_WEB_SPARROW_CONTACT_SALES_URL}",
  VITE_WEB_POSTHOG_CONNECTION_API_KEY: "${VITE_WEB_POSTHOG_CONNECTION_API_KEY}",
  VITE_WEB_POSTHOG_API_URL: "${VITE_WEB_POSTHOG_API_URL}",
  VITE_WEB_API_TIMEOUT: "${VITE_WEB_API_TIMEOUT}",
  VITE_WEB_AUTH_URL: "${VITE_WEB_AUTH_URL}",
  VITE_WEB_GITHUB: "${VITE_WEB_GITHUB}",
  VITE_WEB_LINKEDIN: "${VITE_WEB_LINKEDIN}",
  VITE_WEB_DOWNLOAD_LINK: "${VITE_WEB_DOWNLOAD_LINK}",
  VITE_WEB_RELEASE_NOTES_PAT_TOKEN: "${VITE_WEB_RELEASE_NOTES_PAT_TOKEN}",
  VITE_WEB_RELEASE_NOTES_API: "${VITE_WEB_RELEASE_NOTES_API}",
  VITE_WEB_AZURE_CDN_URL: "${VITE_WEB_AZURE_CDN_URL}",
  VITE_WEB_CANNY_API: "${VITE_WEB_CANNY_API}",
  VITE_WEB_AZURE_INSIGHTS_CONNECTION_STRING: "${VITE_WEB_AZURE_INSIGHTS_CONNECTION_STRING}",
  VITE_WEB_BASE_URL: "${VITE_WEB_BASE_URL}",
  VITE_WEB_MARKETING_URL: "${VITE_WEB_MARKETING_URL}",
  VITE_WEB_SPARROW_DOCS: "${VITE_WEB_SPARROW_DOCS}",
  VITE_WEB_PROXY_SERVICE: "${VITE_WEB_PROXY_SERVICE}",
  VITE_WEB_SOCKET_IO_API_URL: "${VITE_WEB_SOCKET_IO_API_URL}",
  VITE_WEB_APP_ENVIRONMENT_PATH: "${VITE_WEB_APP_ENVIRONMENT_PATH}",
  VITE_WEB_SPARROW_AI_WEBSOCKET: "${VITE_WEB_SPARROW_AI_WEBSOCKET}",
  VITE_WEB_SENTRY_DSN: "${VITE_WEB_SENTRY_DSN}",
  VITE_WEB_APP_ENVIRONMENT: "${VITE_WEB_APP_ENVIRONMENT}",
  VITE_WEB_SPARROW_WEB_APP_URL: "${VITE_WEB_SPARROW_WEB_APP_URL}"
}
EOF
envsubst < "$ROOT/runtime-config.js.tmpl" > "$ROOT/runtime-config.js" || true
rm -f "$ROOT/runtime-config.js.tmpl"

# Helpful log
echo "Generated runtime-config.js:"
sed -n '1,120p' "$ROOT/runtime-config.js"